<template>
  <div curPageName="66f567ab3452433">
    <!-- 保存为常用搜索方案 -->
    
    <el-dialog class="search_plan" v-model="centerDialogVisible" :title="$t('merak.plan_dialog_title')" width="500" align-center>
      <div class="plan-content">
        
        <el-form ref="upFormRef" :model="planForm" :rules="rules" label-width="auto">
          <div class="plan-tips">
            <div class="tips-el-icon">
              <el-icon>
                <WarningFilled />
              </el-icon>
            </div>
               <!-- 提示 -->
            <div class="plan_tooltip_txt" v-html='$t("merak.plan_dialog_upper_limit_prompt")'></div>
          </div>
          <div class="save-type">
            <!-- 保存方式 -->
            {{ $t('merak.plan_save_type') }}
         
         
            <el-radio-group v-model="radioVal" class="ml-4">
              <!-- 新增 -->
              <el-radio  
                value="1"
                label="1"
                size="large"
                :disabled="planoptions.length == planLength ? true : false"
                >
                {{ $t("merak.add") }}
                </el-radio>
              <!-- 更新已有方案 -->
            
              <el-radio v-if="planoptions.length != 0" value="2" label="2" size="large">
                {{ $t("merak.plan_dialog_update_existing")}}
                </el-radio>
            </el-radio-group>
          </div>

          <div class="enter-plan-name" v-if="radioVal == 1">
            <el-row gutter="40">
              <!-- 请输入搜索计划名称 -->
              <el-col :span="16" :offset="4">
                <el-form-item prop="planName">
                  <el-input
                    v-model="planForm.planName"
                    style="width: 100%"
                    :placeholder="$t('merak.plan_enter_name_placeholder')"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="select-plane" v-else>
            <el-row gutter="40" style="margin-bottom: 10px">
              <el-col :span="16" :offset="4">
                <!-- 选择搜索方案 -->
                <el-select :teleported="false" v-model="planVal" clearable :placeholder="$t('merak.plan_select_placeholder')">
                  <el-option v-for="(item, pindex) in planoptions" :key="pindex" :label="item.name" :value="item.id" />
                </el-select>
              </el-col>
              
            </el-row>
            <el-row gutter="40">
              <el-col :span="16" :offset="4">
                <!-- 更新当前搜索方案新名称 -->
                <el-input v-model.trim="upPlanName" style="width: 100%" :placeholder="$t('merak.plan_updata_name_placeholder')" />
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
      <template #footer>

        <div class="dialog-footer"> 
          <!-- 取消 -->
          <el-button @click="close">{{ $t("merak.cancel") }}</el-button>
          <!-- 确认 -->
          <el-button type="primary" @click="updataPlan">{{ $t("merak.confirm") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>



<script lang="ts" setup>
import { onMounted, ref, watchEffect, watch, reactive, nextTick,defineEmits,getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import { planInterFace } from "../index";
import bus from "../bus";
const {proxy}=getCurrentInstance();
const $emit=defineEmits([
   'saveplan'
])

const upFormRef = ref("");
// const props = withDefaults(defineProps<planInterFace>(), {
//   formData: {},
//   valKey: "key",
//   curId:""
// });
const props =defineProps({
  formData: {
    default:()=>{{}}
  },
  valKey: "key",
  curId:"",
  planOptions:{
    default:()=>{[]}
  }
})
 
 
let searchPlanId = ref<string>("");

//可以存储的计划数量上限
const planLength = 5;
let planoptions =reactive([]);
let planName = ref("");
let planVal = ref(null);
let selectPlanName = "";
let upPlanName = ref("");
let radioVal = ref("1");
let centerDialogVisible = ref(false);

 
interface formInterFace {
  planName: string;
}

const planForm = reactive<formInterFace>({
  planName: ""
});

const rules = reactive({
  planName: [{ required: true, message: proxy.$t('merak.plan_updata_name_placeholder') }]
});

// bus.planClose=close;

const modelValue = defineModel<object>({ default: {} });


//life
onMounted(() => {});

//methods

//更新计划
const updataPlan = () => {
  const form = JSON.parse(JSON.stringify(modelValue.value));
  let planId = new Date().getTime();
  let params = {};
  let name = planForm.planName;
  let valueString = ""; //合并所有的value值，判断是否为空，没有选择任何搜索参数
  const getValueText = (value, options) => {
    !Array.isArray(value) ? (value = [value]) : null;
    let valueTexts = [];
    //把数据存起来，选择方案之后直接注入 options 数据，以保证 form 表单的数据完整性
    //暂时不存储 text 数据 ，因为直接写入文本会导致 表单 数据 不完整 影响 其它功能
    value.map(itemValue => {
      let index = options.findIndex(itemOption => {
        return itemOption["value"] == itemValue;
      });

      if (index != -1) {
        valueTexts.push(JSON.parse(JSON.stringify(options[index])));
      }
    });

    return valueTexts;
  };
  const next = () => { 
    Object.keys(form).map(item => { 
      params[item] = form[item]["value"];
      valueString += form[item]["value"]?form[item]["value"] + "":'';
      // params[item + "_text"] = getValueText(form[item]["value"], form[item]?.options ?? []);
      params[item + "_options"] = getValueText(form[item]["value"], form[item]?.options ?? []);
    });
    
    // if (valueString.replaceAll(" ", "").length == 0) {
    //   ElMessage({
    //     message: proxy.$t('merak.plan_no_selected'),
    //     type: "error",
    //     customClass: 'messageIndex'
        
    //   });
    //   return;
    // }
 
    $emit('saveplan',{ id: planId, name: name || selectPlanName, params })
    // bus.savePlan({ id: planId, name: name || selectPlanName, params });
  };

  if (radioVal.value == 2) {
    //判断是选择替换方案
    planId = planVal.value;
    name = upPlanName.value;
    next();
  } else {
    upFormRef.value?.validate(isValid => {
      if (isValid) {
        //验证通过
        next();
      }
    });
  }
};

// 显示更新计划框
const show = () => {
  centerDialogVisible.value = true;
  // planOptions.value = bus.planList[props.curId] ?? [];
  
  planName.value = ""; //清空新增方案名称
  planVal.value = "";
  upPlanName.value = ""; // 
  
 planoptions =Object.assign(planoptions,JSON.parse(JSON.stringify(props.planOptions))) ; 
 
 planoptions.length == planLength ? (radioVal.value = "2") : null;
  nextTick(() => {
    upFormRef.value?.resetFields();
  });
};
const close = () => {
  centerDialogVisible.value = false;
};

//watche
watchEffect(() => {});
watch(planVal, (n, v) => {
  let index = planoptions.findIndex(item => {
    return item.id == n;
  });
  let name =planoptions[index]?.name;
  upPlanName.value = name;
  selectPlanName = name;
});
//暴露方法属性

defineExpose({
  showModal: show,
  closeModal: close
  //   getPlanList: getPlanList
});
</script>



<style lang="scss" scoped>
.plan-content {
  margin-top: -10px;
  margin-bottom: 10px;
  .enter-plan-name {
    // text-align: center;
  }
}
.plan-tips {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  .tips-el-icon {
    color: #e74c3d;
    margin-right: 5px;
  }
  .plan_tooltip_txt {
    color: #82848f;
    font-size: 12px;
    line-height: 17px;
  }
}

.save-type {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 20px;
  /* font-weight: bold; */
  margin: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.select-plane {
  // display: flex;
  // flex-direction: column;
  // align-items: center;
  // gap: 10px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #e6e6ee;
}

:deep(.el-dialog__header) {
  border: none;
}
:deep(.messageIndex){
  z-index: 3000 !important;
}
</style>